package com.app.utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.app.application.MyApplication;
import com.app.config.AppConfig;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.HttpRequest;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.FileUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.utils.secure.EncodeMD5;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.index.activity.IndexWriterBannerActivity;
import com.lepu.app.fun.knowledge.bean.Article;
import com.lepu.app.fun.lottery.AppLotteryActivity;
import com.lepu.app.fun.my.PubContentDetailActivity;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.app.main.activity.AppStartActivity;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.main.bean.BeanAd;
import com.lepu.app.main.push.BeanPush;

public class Utils {

	/*
	 * 程序安装第一次启动后，删除sd卡根目录文件
	 */
	public static void cleanAllFile(final Context context) {
		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					LogUtilBase.LogD(null, "clean all file");

					String filePath = SdLocal.getLepuRootPathSD(context);
					LogUtilBase.LogD(null, "clean all file filePath="+filePath);
					if (!StringUtilBase.stringIsEmpty(filePath)) {
						File file = new File(filePath);
						LogUtilBase.LogD(null, "clean all file state"+file.exists());
						if (file.exists()) {
							FileUtilBase.deleteFile(file);
							LogUtilBase.LogD(null, "clean all file success");
						}
					}
				}catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}).start();
	}

	public static void cleanFile(final Context context, final String filePath,
			final CallBack callBack) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					if (!StringUtilBase.stringIsEmpty(filePath)) {
						File file = new File(filePath);
						if (file.exists()) {
							FileUtilBase.deleteFile(file);
							LogUtilBase.LogD(null, "clean all file");
							if (callBack != null) {
								callBack.callBackSuccess(null);
							}
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}

			}
		}).start();
	}

	public static void cleanAllCache(final Context context,
									 final CallBack callBack) {
		new Thread(new Runnable() {

			@Override
			public void run() {

//				String tempFilePath = SdLocal.getTempFolder(context);
//				if (!StringUtilBase.stringIsEmpty(tempFilePath)) {
//					File tempFile = new File(tempFilePath);
//					if (tempFile.exists()) {
//						FileUtilBase.deleteFile(tempFile);
//						LogUtilBase.LogD(null, "clean tempFile file");
//					}
//				}

				try {
					//image loader cache
					UniversalImageLoadTool.clearAllCache();

					//xutil通用缓存图像
					BitmapLoadUtil.clearAllCache();

					//xutil通用缓存图像
					HeadIconLoadUtil.clearAllCache();
				}catch (Exception e){
					e.printStackTrace();
				}

				if (callBack != null) {
					callBack.callBackSuccess(null);
				}
			}
		}).start();
	}

	/**
	 * 定时清理缓存cache
	 */
	public static void cleanByTime(Context context) {
		try {
			long start = System.currentTimeMillis();
			int lastCleanTime = AppConfig.getConfigInt(context, Const.CONFIG_APP_LAST_CLEAN_TIME, 0);//
			int currentTime = (int) (System.currentTimeMillis() / 1000);

			if(lastCleanTime <= 0) { //第一次运行

			} else {
				if((currentTime - lastCleanTime) > Const.CLEAN_HISTORY_CACHE) {
					//清除过期的缓存文件
					cleanAllCache(context,null);
				}
			}
			AppConfig.setConfig(context,Const.CONFIG_APP_LAST_CLEAN_TIME, currentTime);

			LogUtilBase.LogD(null, "clean: " + (System.currentTimeMillis() - start));
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 字符串需要是 yyyy-MM-dd
	 */
	@SuppressWarnings("unused")
	private static int[] getCacuteTimeDayString(String birthdayString,
			String dateString) {
		Date birthday = DateUtilBase.dateFromString(birthdayString,
				DateUtilBase.YEAR_MONTH_DAY);

		Date date = DateUtilBase.dateFromString(dateString,
				DateUtilBase.YEAR_MONTH_DAY);
		long time = date.getTime() - birthday.getTime();
		int day = (int) (time / 1000 / 60 / 60 / 24);

		int sui = day / 365;
		int tian = day % 365;

		if (sui < 0) {
			sui = 0;
		}

		if (tian < 0) {
			tian = 0;
		}

		int[] array = new int[] { sui, tian };

		return array;
	}
	
	/*
	 * 特殊时间点推送
	 */
	public static boolean getUserPush()
	{
		boolean flag = false;
		
		
		return flag;
	}
	
	public static String getBabyString(String birthday)
	{
		String result = "";
		
		Date birthDate = DateUtilBase.dateFromString(birthday, DateUtilBase.YEAR_MONTH_DAY);
		String dayString = DateUtilBase.stringFromDate(new Date(), DateUtilBase.YEAR_MONTH_DAY);
		Date currentDate = DateUtilBase.dateFromString(dayString, DateUtilBase.YEAR_MONTH_DAY);
		
		long time = currentDate.getTime() - birthDate.getTime();
		if(time > 0)
		{
			int day = (int) (time / 1000 / 60 / 60 / 24);
			
			if(day >= 30)
			{
				int sui = day / 365;

				StringBuilder sb = new StringBuilder();
				sb.append("(宝宝");
				
				if(sui > 0)
				{
					sb.append(String.format("%d岁", sui));
					int month = (day - 365) / 30;
					if(month > 0)
					{
						sb.append(String.format("%d个月", month));
					}
				}else{
					int month = day / 30;
					if(month > 0)
					{
						sb.append(String.format("%d个月", month));
					}
				}
				
				sb.append(")");
				
				result = sb.toString();
			}
		}
		
		return result;
	}
	
	
	 /**
     * 计算两个日期相差多少天
     *
     * @param startTime
     * @param endTime
     * @param format
     * @return
     */
    @SuppressWarnings("unused")
	@SuppressLint("SimpleDateFormat")
	public static long TimeDifference(String startTime, String endTime, String format) {
        // 按照传入的格式生成一个simpledateformate对象
    	
        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        long ns = 1000;// 一秒钟的毫秒数
        long diff = 0;
        long day = 0;
        try {
            // 获得两个时间的毫秒时间差异
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            day = diff / nd;// 计算差多少天
            long hour = diff % nd / nh;// 计算差多少小时
            long min = diff % nd % nh / nm;// 计算差多少分钟
            long sec = diff % nd % nh % nm / ns;// 计算差多少秒

            return day;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return day;
    }
    
//    public static void jumpVideoInfo(BaseFragmentActivity activity,String TargetID)
//    {
//    	if(!TextUtils.isEmpty(TargetID))
//		{
//    		TargetID = TargetID.trim();
//			String[] videoArray = activity.getResources().getStringArray(R.array.array_read_url);
//			int flag = -1;
//			for(int i=0;i<videoArray.length;i++)
//			{
//				if(videoArray[i].equals(TargetID))
//				{
//					flag = i;
//					break;
//				}
//			}
//			if(flag >= 0)
//			{
//				Intent videoIntent = new Intent(activity,
//						KnowledgeReadDetailActivity.class);
//				videoIntent.putExtra("readId",
//						flag);
//				activity.startActivity(
//						videoIntent, true);
//			}else{
//				UIHelper.showToast(activity, "很抱歉，当前没有这个视频");
//			}
//		}
//    }
    
    /**
     * 是否促销  此参数是为了实现特殊的促销引导注册特殊增加积分
				0-非促销
				1-促销
     * @return
     */
//    public static int getIsPromotionValue(Context context)
//    {
//    	int value = 0;
//    	boolean appFirstUse = AppConfig.getConfigBoolean(context,
//				Const.CONFIG_APP_FIRST_USE, true);
//    	if(appFirstUse)
//    	{
//    		value = 1;
//    	}
//    	return value;
//    }
    
    /**
     * 检查程序是否进入了主页面
     * @return
     */
    public static boolean checkIfApplicationMain()
    {
    	boolean flag = false;
    	
    	if(MainTabActivity.getInstance() != null)
    	{
    		flag = true;
    	}
    	
    	return flag;
    }
    
    @SuppressLint("SetJavaScriptEnabled") 
	/**
	 * 
	 * @param webView
	 * @param isLoadData  加载的是data true，加载的是url，false
	 */
	public static void initWebViewSettings(WebView webView,boolean isLoadData)
	{
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSupportZoom(false);
		webSettings.setBuiltInZoomControls(false);
		webSettings.setDefaultTextEncodingName("UTF -8");// 设置默认为utf-8
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		webSettings.setDomStorageEnabled(true);//有些网页加载出来是空白

		//========================
		if(!isLoadData)
		{
			webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
			webSettings.setUseWideViewPort(true);
			webSettings.setLoadWithOverviewMode(true);
		}
		
		//=========================
		webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
	}
    
    @SuppressWarnings("deprecation")
    public static int getBannerHeight16To9(Context context)
    {
    	WindowManager wm = (WindowManager) context.getSystemService(
				Context.WINDOW_SERVICE);
		int width = wm.getDefaultDisplay().getWidth();
		int height = width * 9 / 16;
    	return height;
    }
    
    @SuppressWarnings("deprecation")
    public static int getBannerHeight25To8(Context context)
    {
    	WindowManager wm = (WindowManager) context.getSystemService(
				Context.WINDOW_SERVICE);
		int width = wm.getDefaultDisplay().getWidth();
		int height = width * 8 / 25;
    	return height;
    }

	@SuppressLint("NewApi")
	public static void setStatusBarTranslucent(Activity activity)
	{
		if(activity == null)
		{
			return;
		}

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = activity.getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		}else{
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	public static void setNavigationBarTranslucent(Activity activity)
	{
		if(activity == null)
		{
			return;
		}

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		}
	}

	public static boolean isApplicationMaJia(Context context)
	{
		boolean flag = false;
		String apkType = UtilityBase.getAppMetedata(context,
				"APK_TYPE");
		int value = UtilityBase.parseInt(apkType);
		if (value > 1)
		{
			flag = true;
		}
		return flag;
	}

	public static int getMaJiaType(Context context)
	{
		String apkType = UtilityBase.getAppMetedata(context,
				"APK_TYPE");
		int value = UtilityBase.parseInt(apkType);
		return value;
	}

	public static int getStatusBarHeight(Context context) {
		int result = 0;
		int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = context.getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}

	public static void clickFocusItem(BaseFragmentActivity baseFragmentActivity,Article item)
	{
		// 作家专栏字段不为空
		if (!TextUtils.isEmpty(item.AuthorID)) {

			AppEnterTongJi.clickEvent(75, item.AuthorID);

			Intent intent = new Intent(baseFragmentActivity,
					IndexWriterBannerActivity.class);
			intent.putExtra("AuthorID", item.AuthorID);
			baseFragmentActivity.startActivity(intent, true);
			return;
		}

		if(TextUtils.isEmpty(item.LinkTargetType))
		{
			return;
		}

		if (item.LinkTargetType.equals("-1")) {

			MyNetUtil.getInstance().requestArticleDetail(
					baseFragmentActivity, item.ArticleID,
					item.DisplayType, item.ContentType, "");
		} else if (item.LinkTargetType.equals("0")) {

		} else if (item.LinkTargetType.equals("1")) {
			// 优酷视频播放
			// video
			// 先跳对应的详情页面
			// Utils.jumpVideoInfo(MainTabActivity.getInstance(),
			// item.LinkTargetID);

			MyNetUtil.getInstance().requestArticleDetail(
					baseFragmentActivity, item.ArticleID,
					item.DisplayType, item.ContentType,"");

		} else if (item.LinkTargetType.equals("2")) {
			// 月子大咖详情（晒经验详情）
			// 已经没有了这个功能
		} else if (item.LinkTargetType.equals("3")) {

			AppEnterTongJi.clickEvent(74, item.LinkTargetID);

			// 宝马一起秀详情
			Intent intent = new Intent(baseFragmentActivity,
					PubContentDetailActivity.class);
			intent.putExtra("tag", 0);
			intent.putExtra("TopicId", item.LinkTargetID);
			baseFragmentActivity.startActivity(intent, true);
		} else if (item.LinkTargetType.equals("4")) {

			AppEnterTongJi.clickEvent(74, item.LinkTargetID);

			// 情感八卦详情
			Intent intent = new Intent(baseFragmentActivity,
					PubContentDetailActivity.class);
			intent.putExtra("tag", 1);
			intent.putExtra("TopicId", item.LinkTargetID);
			baseFragmentActivity.startActivity(intent, true);
		} else if (item.LinkTargetType.equals("5")) {
			// Intent intent = new Intent(mContext,
			// MyArticleListActivity.class);
			// intent.putExtra("title", "宝宝发育指南");
			// ((BaseFragmentActivity) mContext).startActivity(intent,
			// true);
			// 现在网页做了
			MyNetUtil.getInstance().requestArticleDetail(
					baseFragmentActivity, item.ArticleID,
					item.DisplayType, item.ContentType, "");
		} else if (item.LinkTargetType.equals("6")) {

			AppEnterTongJi.clickEvent(74, item.LinkTargetID);

			// 抽奖
			Intent lotteryIntent = new Intent(baseFragmentActivity,
					AppLotteryActivity.class);
			lotteryIntent.putExtra("cover", item.Cover);
			lotteryIntent.putExtra("LinkTargetID", item.LinkTargetID);// 抽奖活动id
			baseFragmentActivity.startActivity(lotteryIntent, true);
		} else if(item.LinkTargetType.equals("8"))
		{
			//作家作品文章详情
			MyNetUtil.getInstance().requestArticleDetailWriter(baseFragmentActivity, item.ArticleID);
		}
		else if (item.LinkTargetType.equals("100")) {

			AppEnterTongJi.clickEvent(74, item.LinkURL);

			// 跳转指定链接
			Intent intent = new Intent(baseFragmentActivity,
					AppBroswerActivity.class);
			intent.putExtra("need_share", true);
			intent.putExtra("title", "");
			intent.putExtra("cover", item.Cover);
			intent.putExtra("url", item.LinkURL);
			baseFragmentActivity.startActivity(intent, true);
		}
	}

	public static void clickPush(Context context, BeanPush beanPush)
	{
		BaseFragmentActivity currentActivity = (BaseFragmentActivity) AppManager
				.getAppManager().currentActivity();
		if(currentActivity == null){
			return;
		}

		if (beanPush != null) {
			int type = UtilityBase.parseInt(beanPush.TargetType);
			switch (type) {
				case -1:
				case 5:
					// 文章详情
					// 科学孕育文章详情
					MyNetUtil.getInstance().requestArticleDetail(
							currentActivity, beanPush.TargetID,
							"","","");

					break;
				case 1:
					// 优酷视频
//						Utils.jumpVideoInfo(MainTabActivity.getInstance(),
//								beanPush.TargetID);
					MyNetUtil.getInstance().requestArticleDetail(
							currentActivity, beanPush.TargetID,
							"","","");
					break;
				case 2:
					// 月子大咖详情
					// 不用处理，已去掉这个功能
					break;
				case 3:
				case 4:
					// 宝妈一起秀详情
					// 情感八卦详情
					Intent intent = new Intent(context,
							PubContentDetailActivity.class);
					if (type == 3) {
						intent.putExtra("tag", 0);
					} else {
						intent.putExtra("tag", 1);
					}
					intent.putExtra("TopicId", beanPush.TargetID);
					currentActivity.startActivity(intent, true);
					break;
				case 6:
					// 抽奖详情
					Intent lotteryIntent = new Intent(context,
							AppLotteryActivity.class);
					lotteryIntent.putExtra("LinkTargetID",
							beanPush.TargetID);// 抽奖活动id
					currentActivity.startActivity(lotteryIntent, true);
					break;
				case 7:
					// 热门相册详情
					// 暂时不做这个

					// Intent hotphotoIntent = new Intent(context,
					// GrowHotPhotoDetailActivity.class);
					// MainTabActivity.getInstance().startActivity(
					// hotphotoIntent, true);
					break;
				case 8:
					//作家专栏列表
					if (!TextUtils.isEmpty(beanPush.TargetID)) {

						//作家作品文章详情
						MyNetUtil.getInstance().requestArticleDetailWriter(currentActivity, beanPush.TargetID);
						return;
					}
					break;
				case 100:
					// 跳转指定链接
					Intent urlIntent = new Intent(context,
							AppBroswerActivity.class);
					urlIntent.putExtra("need_share", true);
					urlIntent.putExtra("url", beanPush.TargetURL);
					urlIntent.putExtra("title", "");
					urlIntent.putExtra("cover", "");
					currentActivity.startActivity(urlIntent, true);
					break;
				case 101:
					// 静态图片 不做跳转
					break;
				default:
					break;
			}
		}
	}

	/**
	 *
	 * @param adList
	 */
	public static void dowithAdRequest(ArrayList<BeanAd> adList)
	{
		MyApplication.getInstance().mAdList = adList;
		final MyApplication instance = MyApplication.getInstance();

		if(adList != null && adList.size() > 0)
		{
			for(final BeanAd item : adList)
			{
				final String filePath = SdLocal.getCacheImagePath(instance, EncodeMD5.getMd5(item.Cover));
				final int type = UtilityBase.parseInt(item.ShowLocation);

				if(type == 1)
				{
					//启动页
					new Thread(new Runnable() {
						@Override
						public void run() {

							HttpRequest.downloadFileBy(item.Cover,filePath , new CallBack() {
								@Override
								public void callBackSuccess(Object obj) {
									super.callBackSuccess(obj);
									LogUtilBase.LogD(null, "ad app start download sucess");
								}

								@Override
								public void callBackFail(Object obj) {
									super.callBackFail(obj);
									LogUtilBase.LogD(null, "ad app start download fail");
								}
							});
						}
					}).start();

				}else if(type == 2){
					//首页
					new Thread(new Runnable() {
						@Override
						public void run() {

							HttpRequest.downloadFileBy(item.Cover, filePath, new CallBack() {
								@Override
								public void callBackSuccess(Object obj) {
									super.callBackSuccess(obj);
									LogUtilBase.LogD(null, "ad index download sucess");
								}

								@Override
								public void callBackFail(Object obj) {
									super.callBackFail(obj);
									LogUtilBase.LogD(null, "ad index download fail");
								}
							});
						}
					}).start();

				}else if(type == 3){
					//妈妈圈
					new Thread(new Runnable() {
						@Override
						public void run() {

							HttpRequest.downloadFileBy(item.Cover, filePath, new CallBack() {
								@Override
								public void callBackSuccess(Object obj) {
									super.callBackSuccess(obj);
									LogUtilBase.LogD(null, "ad mother circle download sucess");
								}

								@Override
								public void callBackFail(Object obj) {
									super.callBackFail(obj);
									LogUtilBase.LogD(null, "ad mother circle download fail");
								}
							});
						}
					}).start();
				}
			}
		}
	}

	public static String getAdFilePath(int currentType)
	{
		final MyApplication instance = MyApplication.getInstance();
		String filePath = "";
		ArrayList<BeanAd> adList = MyApplication.getInstance().mAdList;
		if(adList != null && adList.size() > 0)
		{
			for(BeanAd item : adList){
				int type = UtilityBase.parseInt(item.ShowLocation);
				if(type == currentType)
				{
					filePath = SdLocal.getCacheImagePath(instance, EncodeMD5.getMd5(item.Cover));
					break;
				}
			}
		}
		return filePath;
	}

	public static void clickAd(BaseFragmentActivity baseFragmentActivity,int currentType)
	{
		if(baseFragmentActivity == null)
		{
			return;
		}

		ArrayList<BeanAd> adList = MyApplication.getInstance().mAdList;
		if(adList != null && adList.size() > 0)
		{
			for(BeanAd item : adList){
				int type = UtilityBase.parseInt(item.ShowLocation);
				if(type == currentType)
				{
					Article article = new Article();
					article.LinkTargetType = item.LinkTargetType;
					article.LinkURL = item.LinkTargetValue;
					article.LinkTargetID  = item.LinkTargetValue;
					article.ArticleID  = item.LinkTargetValue;
					article.Cover = item.Cover;

					Utils.clickFocusItem(baseFragmentActivity,article);
					break;
				}
			}
		}
	}

	public static void callPhone(final Activity context, final String phone) {
		// if (readSIMCard()) { //没有SIM卡
		// UIHelper.showToast(context, "该设备，未安装sim卡");
		// return;
		// }
		MyDialog myDialog = new MyDialog(context);
		myDialog.setTitle("拨打电话").setMessage(phone)
				.setNegativeButton(R.string.cancel, null)
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Uri uri = Uri.parse("tel:" + phone);
						Intent intentCallPhone = new Intent(Intent.ACTION_DIAL,
								uri);
						context.startActivity(intentCallPhone);

					}
				}).create(null).show();
	}

}
